<template>
  <view class="chat-container">
    <!-- 顶部导航 -->
    <view class="chat-header">
      <text class="title">查询助手</text>
      <view class="header-actions">
        <button class="action-btn" @click="showSessions = !showSessions">
          <uni-icons type="list" size="24"></uni-icons>
        </button>
        <button class="action-btn" @click="newSession">
          <uni-icons type="plus" size="24"></uni-icons>
        </button>
      </view>
    </view>

    <!-- 会话列表弹窗 -->
    <uni-popup v-model="showSessions" type="bottom" :mask="true">
      <view class="sessions-popup">
        <text class="popup-title">我的会话</text>
        <view class="session-item" 
              v-for="(session, index) in sessions" 
              :key="index"
              @click="switchSession(session)">
          <text class="session-text">{{ session | formatSessionId }}</text>
          <button class="delete-btn" @click.stop="deleteSession(session, index)">
            <uni-icons type="trash" size="20" color="#ff4d4f"></uni-icons>
          </button>
        </view>
        <button class="new-session-btn" @click="newSession">+ 新建会话</button>
      </view>
    </uni-popup>

    <!-- 消息区域 -->
    <scroll-view 
      class="message-area" 
      scroll-y 
      :scroll-top="scrollTop"
      @scroll="onScroll"
      ref="scrollView"
    >
      <!-- 空状态 -->
      <view class="empty-state" v-if="messages.length === 0 && !isLoading">
        <uni-icons type="chat" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">开始你的查询吧~</text>
      </view>

      <!-- 消息列表 -->
      <view 
        class="message-item" 
        v-for="(msg, index) in messages" 
        :key="index"
        :class="{ 'user-msg': msg.role === 'user', 'ai-msg': msg.role === 'assistant' }"
      >
        <view class="avatar">
          <image 
            :src="msg.role === 'user' ? '/static/user.png' : '/static/ai.png'" 
            mode="widthFix"
          ></image>
        </view>
        <view class="message-content">
          <text class="content-text">{{ msg.content }}</text>
          <text class="time-text">{{ msg.timestamp | formatTime }}</text>
        </view>
      </view>

      <!-- 加载中 -->
      <view class="loading-state" v-if="isLoading">
        <uni-loading-icon size="24" type="circle"></uni-loading-icon>
        <text class="loading-text">正在思考...</text>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <textarea 
        class="input-box" 
        v-model="inputContent" 
        placeholder="请输入查询内容..."
        @confirm="sendQuery"
        :auto-height="true"
        maxlength="500"
      ></textarea>
      <button 
        class="send-btn" 
        @click="sendQuery"
        :disabled="!inputContent.trim() || isLoading"
      >
        发送
      </button>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  filters: {
    // 格式化会话ID显示
    formatSessionId(sessionId) {
      if (!sessionId) return ''
      // 只显示最后8位便于识别
      return sessionId.length > 8 ? sessionId.slice(-8) : sessionId
    },
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  },
  data() {
    return {
      inputContent: '', // 输入内容
      messages: [], // 消息列表
      sessionId: '', // 当前会话ID
      sessions: [], // 会话列表
      isLoading: false, // 加载状态
      showSessions: false, // 显示会话列表
      scrollTop: 0, // 滚动位置
      needScrollBottom: true // 是否需要滚动到底部
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  onLoad() {
    // 初始化页面
    this.init()
  },
  methods: {
    // 初始化
    init() {
      // 加载用户会话列表
      this.loadSessions()
    },

    // 加载会话列表
    loadSessions() {
      this.$http.get('/chat/query/sessions').then(res => {
        if (res.code === 200) {
          this.sessions = res.data || []
          // 如果有会话，默认选择第一个
          if (this.sessions.length > 0) {
            this.switchSession(this.sessions[0])
          } else {
            // 没有会话则创建新会话
            this.newSession()
          }
        }
      }).catch(err => {
        console.error('加载会话失败', err)
        uni.showToast({ title: '加载会话失败', icon: 'none' })
      })
    },

    // 新建会话
    newSession() {
      this.$http.post('/chat/query/session').then(res => {
        if (res.code === 200) {
          this.sessionId = res.data
          this.messages = []
          // 添加到会话列表头部
          this.sessions.unshift(this.sessionId)
          this.showSessions = false
          uni.showToast({ title: '新会话创建成功', icon: 'none' })
        }
      }).catch(err => {
        console.error('创建会话失败', err)
		this.showSessions = false  //测试临时用
        uni.showToast({ title: '创建会话失败', icon: 'none' })
      })
    },

    // 切换会话
    switchSession(sessionId) {
      if (!sessionId) return
      
      this.sessionId = sessionId
      this.isLoading = true
      this.showSessions = false
      
      // 加载会话历史
      this.$http.get(`/chat/query/history/${sessionId}`).then(res => {
        this.isLoading = false
        if (res.code === 200) {
          this.messages = res.data || []
          this.scrollToBottom()
        } else {
          uni.showToast({ title: '加载历史失败', icon: 'none' })
        }
      }).catch(err => {
        this.isLoading = false
        console.error('加载历史失败', err)
        uni.showToast({ title: '加载历史失败', icon: 'none' })
      })
    },

    // 删除会话
    deleteSession(sessionId, index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个会话吗？',
        success: (res) => {
          if (res.confirm) {
            this.$http.delete(`/chat/query/session/${sessionId}`).then(res => {
              if (res.code === 200) {
                this.sessions.splice(index, 1)
                // 如果删除的是当前会话
                if (sessionId === this.sessionId) {
                  if (this.sessions.length > 0) {
                    this.switchSession(this.sessions[0])
                  } else {
                    this.newSession()
                  }
                }
                uni.showToast({ title: '删除成功', icon: 'none' })
              }
            }).catch(err => {
              console.error('删除会话失败', err)
              uni.showToast({ title: '删除失败', icon: 'none' })
            })
          }
        }
      })
    },

    // 发送查询请求
    sendQuery() {
      const content = this.inputContent.trim()
      if (!content) return
      
      this.isLoading = true
      // 清空输入框
      this.inputContent = ''
      
      // 添加用户消息到列表
      const userMsg = {
        role: 'user',
        content,
        timestamp: new Date()
      }
      this.messages.push(userMsg)
      this.scrollToBottom()

      // 发送HTTP请求
      this.$http.post('/chat/query/send', {
        sessionId: this.sessionId,
        query: content
      }, {
        headers: {
          'Authorization': 'Bearer ' + ''
        }
      }).then(res => {
        this.isLoading = false
        if (res.code === 200) {
          // 更新会话ID（可能创建了新会话）
          this.sessionId = res.data.sessionId
          // 更新消息列表（包含回复）
          this.messages = res.data.history
          this.scrollToBottom()
        } else {
          uni.showToast({ title: '查询失败', icon: 'none' })
          // 移除刚才添加的用户消息（因为发送失败）
          this.messages.pop()
        }
      }).catch(err => {
        this.isLoading = false
        console.error('查询失败', err)
        uni.showToast({ title: '网络错误', icon: 'none' })
        // 移除刚才添加的用户消息
        this.messages.pop()
      })
    },

    // 滚动到底部
    scrollToBottom() {
      this.needScrollBottom = true
      // 延迟执行确保DOM更新
      setTimeout(() => {
        const query = uni.createSelectorQuery().in(this)
        query.select('.message-area').boundingClientRect(data => {
          this.scrollTop = data.scrollHeight
        }).exec()
      }, 100)
    },

    // 监听滚动
    onScroll(e) {
      // 当用户手动滚动时，取消自动滚动到底部
      if (e.detail.scrollTop < this.scrollTop - 50) {
        this.needScrollBottom = false
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 24rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
}

.action-btn {
  background: transparent;
  border: none;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10rpx;
}

/* 会话列表弹窗 */
.sessions-popup {
  width: 100%;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 20rpx;
}

.popup-title {
  font-size: 30rpx;
  font-weight: bold;
  padding: 10rpx 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 20rpx;
  display: block;
}

.session-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.session-text {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.delete-btn {
  background: transparent;
  border: none;
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.new-session-btn {
  width: 100%;
  background-color: #007aff;
  color: #fff;
  border-radius: 30rpx;
  padding: 15rpx 0;
  margin-top: 20rpx;
  font-size: 28rpx;
}

/* 消息区域 */
.message-area {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300rpx;
  color: #ccc;
}

.empty-text {
  font-size: 28rpx;
  margin-top: 20rpx;
}

.message-item {
  display: flex;
  margin-bottom: 30rpx;
  max-width: 85%;
}

.user-msg {
  flex-direction: row-reverse;
  margin-left: auto;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  overflow: hidden;
}

.avatar image {
  width: 100%;
  height: 100%;
}

.user-msg .avatar {
  margin-left: 15rpx;
  margin-right: 0;
}

.ai-msg .avatar {
  margin-right: 15rpx;
  margin-left: 0;
}

.message-content {
  position: relative;
  padding: 18rpx 24rpx;
  border-radius: 18rpx;
  line-height: 1.6;
}

.user-msg .message-content {
  background-color: #007aff;
  color: #fff;
}

.ai-msg .message-content {
  background-color: #fff;
  border: 1px solid #eee;
  color: #333;
}

.content-text {
  font-size: 28rpx;
  display: block;
}

.time-text {
  font-size: 20rpx;
  margin-top: 8rpx;
  display: block;
  opacity: 0.7;
  text-align: right;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
}

.loading-text {
  font-size: 26rpx;
  color: #666;
  margin-left: 10rpx;
}

/* 输入区域 */
.input-area {
  display: flex;
  padding: 15rpx;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.input-box {
  flex: 1;
  min-height: 60rpx;
  max-height: 200rpx;
  padding: 15rpx 20rpx;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  font-size: 28rpx;
  line-height: 1.5;
}

.send-btn {
  width: 100rpx;
  height: 60rpx;
  margin-left: 15rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 30rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:disabled {
  background-color: #ccc;
}
</style>
    